<?php
namespace V1\Controller;

use V1\Logic\StockLogic;

class StockController extends BaseController {
    
     protected $errorCode = array(
        'follow' => array(
            '-1'=>'用户token失效或有误',
            '-10'=>'股票信息不存在',
            '-11'=>'该股票已添加',
        ) ,
        'cancel' => array(
            '-1'=>'用户token失效或有误',
            '-10'=>'数据不存在',
            '-11'=>'该股票未添加',
        ) ,
        'info' => array(
            '-1'=>'用户token失效或有误',
            '-2'=>'参数异常',
        ) ,
        'news' => array(
            '-1'=>'用户token失效或有误',
            '-2'=>'参数异常',
            '-10'=>'数据木有啦',
        ) ,
        
    );

    /**
     * 股票大盘指数
     * 
     */
    public function market(){
       //获取最新的大盘综合指数
        $data = array("code" => 0,"msg" => "","info"=>array());
        $data['info']=StockLogic::getMarketIndex($this->day);
        $this->responseResult($data);
    }
    /**
     * 获取k线数据
     * 
     */
    public function kline($stockcode=NULL){
        if(isset($stockcode)){
            $data = array("code" => 0,"msg" => "","info"=>array());
            $stockcode = getStockWithFlag($stockcode);
            $lines=[
               'min'=>"http://image.sinajs.cn/newchart/min/n/{$stockcode}.gif",
               'daily' =>"http://image.sinajs.cn/newchart/daily/n/{$stockcode}.gif",
               'weekly' =>"http://image.sinajs.cn/newchart/daily/n/{$stockcode}.gif",
               'monthly' =>"http://image.sinajs.cn/newchart/monthly/n/{$stockcode}.gif",
            ];
            $data['info']=$lines;
            $this->responseResult($data);
        }
    }
    /**
     * 股票详情
     */
    public function info(){
         
        $data = array("code" => 0,"msg" => "","info"=>array());

        $stockcode = I('stockcode','');
        
        if(empty($stockcode)) {
            return $this->responseError('-2',200);
        }
        
        $stockInfo = StockLogic::getStockInfo($this->day,getStockWithFlag($stockcode));
        
        $data['info'] = $stockInfo;
        $this->responseResult($data);
    }
    
    public function news(){
        
        $data = array("code" => 0,"msg" => "","info"=>array());

        $stockcode = I('stockcode','');
        
        if(empty($stockcode)) {
            return $this->responseError('-2',200);
        }
        if(preg_match("/^sh|sz/i", $stockcode)){
          $stockcode=substr($stockcode,2);
        }
         $redis = new \Redis();
         $redis->connect('127.0.0.1', 6379);

         if(!$redis->exists($stockcode)){
             $data['msg'] = "无相关新闻";
         }else{
             $resultNewsList = json_decode($redis->get($stockcode),true);
  
             $newsList=[];
             foreach ($resultNewsList['list'] as $key => $value) {
                 if(!preg_match("æ|ä", $value['document.title'])){
                      $newsList[]=$value;
                 }
                 if($key==9){
                     break;
                 }
             }
             $data['info'] = $newsList;
         }
//        $pageSize = I('r',6,'intval');
//        $pageIndex = I('p',1,'intval');
//        $news_type = I('t',0,'intval');
//        
//        $pageIndex>10 && $this->responseError(-10);
//        
//        $where ="stockcode={$stockcode}";
//        $orders =array();
//        if($news_type==1){
//            $where .=' AND (positive-negative)>0';
//        }else if($news_type==2){
//            $where .= ' AND (positive-negative)<0';
//        }
//
//        $fields=['newsid','positive','negative','published'];
//        
//        $newList = M('NewsTag','stock_',C('DB_MT_CORE'))->where($where)->field($fields)
//                ->order('published desc')->page($pageIndex,$pageSize)->cache(true,3600)->select();
//        
//        $resultNewsList =[];
//        
//        $newsModel =  M('News','stock_',C('DB_MT_CORE'));
//        $fields=['title','fragment','url'];
//        foreach ($newList as $key => $value) {
//            
//            $where=array('state'=>1,'id'=>$value['newsid'],'title'=>array('notlike',array('%å%','%æ%'),'OR'));
//            $result = $newsModel->where($where)->field($fields)->cache(true,3600)->find();
//            if(empty($result))                continue;
//            $value['positive']=  round($value['positive'], 2);
//            $value['negative']=  round($value['negative'], 2);
//            $resultNewsList[] = array_merge($result,$value);
//        }
//        unset($newList);
        
        $this->responseResult($data);
    }

    /**
     * 关注股票---todo 需调整
     */
    public function follow() {
       
       $data = array("code" => 0,"msg" => "","info"=>array());
        
       list($uid,$user_token) = $this->checkUserToken();
       
       //获取股票基本信息
       $stockInfo = $this->find('StockInfo',['state'=>1]);
       empty($stockInfo) && $this->responseError(-10);
       if(is_array($stockInfo)){
           foreach ($stockInfo as $value) {
               $isExistUserStock = M('UserStock')->where(['status'=>1,'user_id'=>$uid,'stock_id'=>$value['id']])->find();
               !empty($isExistUserStock) && $this->responseError(-11);
               //保存自选股信息
                $maps=array(
                    'user_id'=>$uid,
                    'stock_id'=>$value['id'],
                    'stock_code'=>$value['stockcode'],
                    'stock_name'=>$value['stockname'],
                    'create_time'=>NOW_TIME,
                    'update_time'=>NOW_TIME,
                    'status'=>1,
                );
                
                $this->save('UserStock', $maps);
           }
           $this->responseResult($data);
       }
    }
    /**
     * 取消关注 ---todo 需调整
     */
    public function cancel() {
        $data = array("code" => 0,"msg" => "","info"=>array());
        
        list($uid,$user_token) = $this->checkUserToken();
        
        $stockInfo = $this->find('StockInfo',['state'=>1]);
        empty($stockInfo) && $this->responseError(-10);
       
        if(is_array($stockInfo)){
            $model = M('UserStock');
           foreach ($stockInfo as $value) {
               
               $isExistUserStock = $model->where(['status'=>1,'user_id'=>$uid,'stock_id'=>$value['id']])->find();
             
               empty($isExistUserStock) && $this->responseError(-11);
     
                $maps=array(
                    'id'=>$isExistUserStock['id'],
                    'update_time'=>NOW_TIME,
                    'status' => 0,
                );
                
                $model->save($maps);
           }
           $this->responseResult($data);       
        
        
    }
    
}
}